package com.ruoyi.project.system.goodsteam.controller;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.uniquekey.IdGererateFactory;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.system.goods.img.domain.GoodsImg;
import com.ruoyi.project.system.goods.img.enums.GoodsImgType;
import com.ruoyi.project.system.goods.img.service.IGoodsImgService;
import com.ruoyi.project.system.goods.product.domain.GoodsProduct;
import com.ruoyi.project.system.goods.product.enums.GoodsProductStatus;
import com.ruoyi.project.system.goods.product.service.IGoodsProductService;
import com.ruoyi.project.system.goodsteam.domain.GoodsTeam;
import com.ruoyi.project.system.goodsteam.service.IGoodsTeamService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 拼团商品列表Controller
 * 
 * @author f_baisi
 * @date 2021-03-02
 */
@Controller
@RequestMapping("/system/goodsteam")
public class GoodsTeamController extends BaseController
{
    private String prefix = "system/goodsteam";

    @Autowired
    private IGoodsTeamService goodsTeamService;
    @Autowired
    private IGoodsProductService goodsProductService;
    @Autowired
    private IGoodsImgService goodsImgService;
    @Autowired
    private IdGererateFactory idGererateFactory;

    @RequiresPermissions("system:goodsteam:view")
    @GetMapping()
    public String goodsteam()
    {
        return prefix + "/goodsteam";
    }

    /**
     * 查询拼团商品列表列表
     */
    @RequiresPermissions("system:goodsteam:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(GoodsTeam goodsTeam)
    {
        startPage();
        List<GoodsTeam> list = goodsTeamService.selectGoodsTeamList(goodsTeam);
        return getDataTable(list);
    }

    /**
     * 导出拼团商品列表列表
     */
    @RequiresPermissions("system:goodsteam:export")
    @Log(title = "拼团商品列表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(GoodsTeam goodsTeam)
    {
        List<GoodsTeam> list = goodsTeamService.selectGoodsTeamList(goodsTeam);
        ExcelUtil<GoodsTeam> util = new ExcelUtil<GoodsTeam>(GoodsTeam.class);
        return util.exportExcel(list, "goodsteam");
    }

    /**
     * 新增拼团商品列表
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存拼团商品列表
     */
    @RequiresPermissions("system:goodsteam:add")
    @Log(title = "拼团商品列表", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(GoodsTeam goodsTeam, String[] imgBannerUrl, String[] imgBannerRealPath,
                              String[] imgDetailsUrl, String[] imgDetailsRealPath,
                              String products)
    {
        goodsTeam.setId(UUID.randomUUID().toString().replace("-",""));
        goodsTeam.setCreateAt(new Date());
        goodsTeam.setMonthlySales(0L);
        goodsTeam.setSpec("[{\"spec_name\":\"通用\",\"spec_values\":[{\"spec_value_name\":\"通用\"}]}]");
        //添加商品信息
        goodsTeamService.insertGoodsTeam(goodsTeam);


        //添加产品信息
        List<Map<String,Object>> productArr = (List<Map<String,Object>>) JSON.parse(products);
        for(Map<String,Object> product:productArr){
            GoodsProduct goodsProduct = new GoodsProduct();
            goodsProduct.setIcon((String) product.get("icon"));
            goodsProduct.setIconReal((String) product.get("iconReal"));
            goodsProduct.setGoodsId(goodsTeam.getId());
            goodsProduct.setStock(Integer.parseInt((String) product.get("stock")));
            goodsProduct.setIsDefault(1);
            String spec = (String) product.get("spec");
            //通过规格获取名称
            StringBuffer bufName = new StringBuffer();
            if (spec.contains("*") && spec.contains(":")) {
                String[] str = StringUtils.split(spec, "*");
                for (String temp : str) {
                    String[] s = StringUtils.split(temp, ":");
//						name += s[1] + " ";
                    bufName.append(s[1] + " ");
                }
            } else if (spec.contains(":")) {
                String[] s = StringUtils.split(spec, ":");
//					name = s[1];
                bufName.append(s[1]);
            }

            goodsProduct.setName("通用");

            goodsProduct.setNumSale(0L);
            goodsProduct.setPriceO(new BigDecimal((String) product.get("price")));
            goodsProduct.setPriceN(new BigDecimal((String) product.get("price")));
            goodsProduct.setPriceVip(new BigDecimal((String) product.get("priceT")));
            goodsProduct.setStatus(GoodsProductStatus.NORMAL.getValue());
            //规格
            goodsProduct.setSpec("通用:通用");
            this.goodsProductService.insertGoodsProduct(goodsProduct);
            //主图信息修改
//            this.uploadFileService.updateUploadFileByRealPaths(Arrays.asList(goodsProduct.getIconReal()),new UploadFile(null,null,null,goodsProduct.getId()));
        }


        if(imgBannerUrl!=null){
            //商品轮播图
            for (int i = 0; i < imgBannerUrl.length; i++) {
                GoodsImg goodsImg = new GoodsImg();
                goodsImg.setSort(Integer.toUnsignedLong(i));
                goodsImg.setGoodsId(goodsTeam.getId());
                goodsImg.setUrl(imgBannerUrl[i]);
                goodsImg.setUrlRealPath(imgBannerRealPath[i]);
                goodsImg.setType(GoodsImgType.BANNER.getValue());
                this.goodsImgService.insertGoodsImg(goodsImg);
                //主图信息修改
//                this.uploadFileService.updateUploadFileByRealPaths(Arrays.asList(imgBannerRealPath[i]),new UploadFile(null,null,null,goodsImg.getId()));
            }
        }
        if(imgDetailsUrl!=null){
            //商品详情
            for (int i = 0; i < imgDetailsUrl.length; i++) {
                GoodsImg goodsImg = new GoodsImg();
                goodsImg.setSort(Integer.toUnsignedLong(i));
                goodsImg.setGoodsId(goodsTeam.getId());
                goodsImg.setUrl(imgDetailsUrl[i]);
                goodsImg.setUrlRealPath(imgDetailsRealPath[i]);
                goodsImg.setType(GoodsImgType.DETAILS.getValue());
                this.goodsImgService.insertGoodsImg(goodsImg);
                //主图信息修改
//                this.uploadFileService.updateUploadFileByRealPaths(Arrays.asList(imgDetailsRealPath[i]),new UploadFile(null,null,null,goodsImg.getId()));
            }
        }
        return AjaxResult.success();
    }

    /**
     * 修改拼团商品列表
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap)
    {
        GoodsTeam goodsTeam = goodsTeamService.selectGoodsTeamById(id);
        mmap.put("goodsTeam", goodsTeam);
        List<GoodsProduct> goodsProductList = this.goodsProductService.findListByGoodsId(id);
        mmap.put("goodsProducts",goodsProductList);
        mmap.put("goodsBanner",this.goodsImgService.findListByGoodsIdAndType(id,GoodsImgType.BANNER.getValue()));
        mmap.put("goodsDetails",this.goodsImgService.findListByGoodsIdAndType(id,GoodsImgType.DETAILS.getValue()));
        mmap.put("productNum",goodsProductList.size());
        return prefix + "/edit";
    }

    /**
     * 修改保存拼团商品列表
     */
    @RequiresPermissions("system:goodsteam:edit")
    @Log(title = "拼团商品列表", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(GoodsTeam goodsTeam, String[] imgBannerUrl, String[] imgBannerRealPath,
                               String[] imgDetailsUrl, String[] imgDetailsRealPath,
                               String products)
    {

        //更新商品信息
        goodsTeam.setId(goodsTeam.getId());
        goodsTeamService.updateGoodsTeam(goodsTeam);

//        GoodsTeam oldGoods = this.goodsTeamService.selectGoodsTeamById(goodsTeam.getId());

        // 判断商品轮播不为空
        if(imgBannerUrl != null){
            //删除数据库原本的相册资源
            this.goodsImgService.deleteByGoodsIdAndType(goodsTeam.getId(),0);
        }
        // 判断商品详情图不为空
        if(imgDetailsUrl != null){
            //删除数据库原本的相册资源
            this.goodsImgService.deleteByGoodsIdAndType(goodsTeam.getId(),1);
        }


        //添加产品信息
        if(!StringUtils.isBlank(products)){
            //删除原本存在的产品信息
            this.goodsProductService.removeByGoodsId(goodsTeam.getId());
            List<Map<String,Object>> productArr = (List<Map<String,Object>>) JSON.parse(products);
            for(Map<String,Object> product:productArr){
                GoodsProduct goodsProduct = new GoodsProduct();
                goodsProduct.setIcon((String) product.get("icon"));
                goodsProduct.setIconReal((String) product.get("iconReal"));
                goodsProduct.setGoodsId(goodsTeam.getId());
                goodsProduct.setStock(Integer.parseInt((String) product.get("stock")));
                goodsProduct.setIsDefault(1);
                String spec = (String) product.get("spec");
                //通过规格获取名称
                StringBuffer bufName = new StringBuffer();
                if (spec.contains("*") && spec.contains(":")) {
                    String[] str = StringUtils.split(spec, "*");
                    for (String temp : str) {
                        String[] s = StringUtils.split(temp, ":");
//						name += s[1] + " ";
                        bufName.append(s[1] + " ");
                    }
                } else if (spec.contains(":")) {
                    String[] s = StringUtils.split(spec, ":");
//					name = s[1];
                    bufName.append(s[1]);
                }

                goodsProduct.setName("通用");

                goodsProduct.setNumSale(0L);
                goodsProduct.setPriceO(new BigDecimal((String) product.get("price")));
                goodsProduct.setPriceN(new BigDecimal((String) product.get("price")));
                goodsProduct.setPriceVip(new BigDecimal((String) product.get("priceT")));
                goodsProduct.setStatus(GoodsProductStatus.NORMAL.getValue());
                //规格
                goodsProduct.setSpec("通用:通用");
                this.goodsProductService.insertGoodsProduct(goodsProduct);
//                sumStock+=goodsProduct.getStock();
                //主图信息修改
//                this.uploadFileService.updateUploadFileByRealPaths(Arrays.asList(goodsProduct.getIconReal()),new UploadFile(null,null,null,goodsProduct.getId()));
            }
        }


        if(imgBannerUrl!=null){
            //商品轮播
            for (int i = 0; i < imgBannerUrl.length; i++) {
                GoodsImg goodsImg = new GoodsImg();
                goodsImg.setSort(Integer.toUnsignedLong(i));
                goodsImg.setGoodsId(goodsTeam.getId());
                goodsImg.setUrl(imgBannerUrl[i]);
                goodsImg.setUrlRealPath(imgBannerRealPath[i]);
                goodsImg.setType(GoodsImgType.BANNER.getValue());
                this.goodsImgService.insertGoodsImg(goodsImg);
                //主图信息修改
//                this.uploadFileService.updateUploadFileByRealPaths(Arrays.asList(imgBannerRealPath[i]),new UploadFile(null,null,null,goodsImg.getId()));
            }
        }
        if(imgDetailsUrl!=null){
            //商品详情
            for (int i = 0; i < imgDetailsUrl.length; i++) {
                GoodsImg goodsImg = new GoodsImg();
                goodsImg.setSort(Integer.toUnsignedLong(i));
                goodsImg.setGoodsId(goodsTeam.getId());
                goodsImg.setUrl(imgDetailsUrl[i]);
                goodsImg.setUrlRealPath(imgDetailsRealPath[i]);
                goodsImg.setType(GoodsImgType.DETAILS.getValue());
                this.goodsImgService.insertGoodsImg(goodsImg);
                //主图信息修改
//                this.uploadFileService.updateUploadFileByRealPaths(Arrays.asList(imgDetailsRealPath[i]),new UploadFile(null,null,null,goodsImg.getId()));
            }
        }
        return AjaxResult.success();
    }

    /**
     * 删除拼团商品列表
     */
    @RequiresPermissions("system:goodsteam:remove")
    @Log(title = "拼团商品列表", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(goodsTeamService.deleteGoodsTeamByIds(ids));
    }
}
